<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\OSS;
use Illuminate\Support\Facades\Validator;

class UploadController extends Controller
{
    //

    private $bucket;
    private $folder;

    public function __construct()
    {
        $this->bucket = env('OSS_BUCKET_NAME');
        $this->folder = env('OSS_FOLDER');
    }


    public function upload(Request $request){ //本地上传

        $file = $request->file('file');
        if($file->isValid()){
            $path = $file->store(date('ymd'),'upload');
            return response()->json([
                'code'=>1,
                'msg'=>'上传成功',
                'data'=>[
                    'path'=>'yysblog/'.$path
                ]
            ]);
        }else{
            return response()->json(['code'=>0,'msg'=>'文件无效,上传错误！']);
        }
    }

    public function cancel_img(Request $request){  //OSS删除文章
        $validator = Validator::make($request->all(['img_name']), [
            'img_name' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'code' => 0,
                'msg' => $validator->messages()->first(),
                'data' => []
            ]);
        }
        $newName = $request->input('img_name');

        OSS::publicDeleteObject($this->bucket, $this->folder.'/'.$newName);
        return response()->json([
            'code' => 1,
            'msg' =>'删除成功',
        ]);
    }
    public function get_test(Request $request){
        dd($request->server('SERVER_ADDR'));
    }

    public function oss_upload(Request $request){ //OSS上传图片

        $file = $request->file('file');
        if($file->isValid()){
            $clientName = $file->getClientOriginalName();
            $entension = $file->getClientOriginalExtension();
            $newName = md5(date('ymd').$clientName).'.'.$entension;
            $content_type = mime_content_type($file->getRealPath());
            $path = $file->getRealPath();
            $result =  OSS::publicUpload($this->bucket,$this->folder.'/'.$newName,$path,[
                'ContentType' => $content_type,
            ]);
            $url = OSS::getPublicObjectURL($this->bucket, $this->folder.'/'.$newName);
            if($result){
                return response()->json([
                    'code'=>1,
                    'msg'=>'上传成功',
                    'url'=>$url,
                    'relative_url'=>$newName
                ]);
            }
        }
    }

}
